package com.rzico.basics.service;


import com.alibaba.fastjson.JSON;
import com.rzico.basics.entity.Product;
import com.rzico.basics.plugin.jd.JDProductInfo;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.basics.plugin.jd.JDStockInfo;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.service.SysPluginService;
import com.rzico.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 京东商品服务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class JdProductService {

    @Autowired
    public SysPluginService sysPluginService;

    @Autowired
    public ProductService productService;

    /**
     * 判断京东商品各个sku的可售性，上下架状态及库存数量，若未上架、不可售或库存不足，系统中商品库存数量直接设为0
     * @param goodsId
     * @param mchId
     * @return
     */
    public void checkJdProduct(Long goodsId, String mchId){
        String token = JDServiceUtils.refrash_token();//获取京东api的token
        Product product = new Product();
        product.setGoodsId(goodsId);
        List<Product> products = productService.select(product);
        for (Product prod:products) {
            boolean saleSign = true;//商品下架标识
            String skuId = prod.getSn().substring(3, prod.getSn().length());
            JDProductInfo jdp1 = JDServiceUtils.selectJDProductState(token, skuId);
            JDProductInfo jdp2 = JDServiceUtils.selectJDProductSaleState(token, skuId);
            if ("0".equals(jdp1.getState()) || "0".equals(jdp2.getSaleState())
                    || StringUtils.isEmpty(jdp2.getIsCanVAT()) || "0".equals(jdp2.getIsCanVAT())) {
                saleSign = false;
            }
            if (saleSign) {
                SysPlugin sysplugin = sysPluginService.findByPlugin(mchId, "marketJDPlugin");
                Map<String, Object> skuParam = new HashMap<String, Object>();
                skuParam.put("skuId", skuId);
                skuParam.put("num", 100);
                String skuNums = "[" + JSON.toJSONString(skuParam) + "]";
                String area = sysplugin.getAttribute("invoiceProvice") + "_" + sysplugin.getAttribute("invoiceCity")
                        + "_" + sysplugin.getAttribute("invoiceCounty");
                JDStockInfo stockInfo = JDServiceUtils.getStock(token, skuNums, area);
                if (!"33".equals(stockInfo.getStockStateId()) && !"39".equals(stockInfo.getStockStateId())
                        && !"40".equals(stockInfo.getStockStateId())) {
                    saleSign = false;
                }
            }
            if (!saleSign) {
                prod.setStock(0);
                productService.updateByPrimaryKey(prod);
            }
        }

    }


}
